CODE 135. Copy List with Random Pointer

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/23/2013-11-23-CODE 135 Copy List with Random Pointer/

访问原文「CODE 135. Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public RandomListNode copyRandomList(RandomListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
Map<Integer, RandomListNode> map = new HashMap<Integer, RandomListNode>();
RandomListNode cpyList = new RandomListNode(0);
RandomListNode cpyListTmp = cpyList;
RandomListNode headTmp = head;
while (null != headTmp) {
int val = headTmp.label;
if (map.containsKey(val)) {
RandomListNode newnode = map.get(val);
cpyListTmp.next = newnode;
cpyListTmp = cpyListTmp.next;
headTmp = headTmp.next;
} else {
RandomListNode newnode = new RandomListNode(val);
cpyListTmp.next = newnode;
cpyListTmp = cpyListTmp.next;
headTmp = headTmp.next;
map.put(val, newnode);
}
}
cpyListTmp = cpyList;
headTmp = head;
while (null != headTmp) {
if (null == headTmp.random) {
cpyListTmp.next.random = null;
} else {
cpyListTmp.next.random = map.get(headTmp.random.label);
}
cpyListTmp = cpyListTmp.next;
headTmp = headTmp.next;
}
return cpyList.next;
}
Jerky Lu wechat
欢迎加入微信公众号